<template>
  <van-button
    class="follow-btn"
    round
    size="small"
    v-if="is_followed"
    @click="onFollow"
    :loading="followLoading"
    >已关注</van-button
  >
  <van-button
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    v-else
    @click="onFollow"
    :loading="followLoading"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/artical.js';
export default {
  name: 'UserFollow',
  props: {
    is_followed: {
      type: Boolean,
      required: true,
    },
    userId: {
      type: [String, Number, Object],
      required: true,
    },
  },
  data() {
    return {
      // 控制loading的显示和隐藏
      followLoading: false,
    };
  },
  methods: {
    async onFollow() {
      // 请求开始，将loading展示出来
      this.followLoading = true;
      try {
        if (this.is_followed) {
          // 已关注用户,则点击取消关注
          await deleteFollow(this.userId);
          // this.isFollowed = false;
        } else {
          await addFollow(this.userId);
          // this.isFollowed = true;
        }
      } catch (err) {
        console.log(err);
        let message = '操作失败，请点击重试！';
        if (err.response && err.response.status === 400) {
          message = '不能关注用户本身！';
        }
        this.$toast(message);
      }
      // this.is_followed = !this.is_followed;
      // 发起通知，来通知父组件更新视图
      this.$emit('updateView', !this.is_followed);
      // 请求结束，将loading隐藏起来
      this.followLoading = false;
    },
  },
};
</script>

<style lang="less" scoped></style>
